{% extends "base.html" %}

{% block title %}{{ evaluation.name }} - 评估详情 - {{ super() }}{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold">评估详情</h1>
        <div class="flex gap-2">
            <a href="{{ url_for('evaluations.evaluations_list') }}" class="btn btn-outline btn-sm">
                <i class="fas fa-arrow-left mr-1"></i> 返回列表
            </a>
            <button class="btn btn-error btn-sm" onclick="document.getElementById('delete-modal').checked = true">
                <i class="fas fa-trash mr-1"></i> 删除评估
            </button>
        </div>
    </div>

    <!-- 评估状态卡片 -->
    <div class="card bg-base-100 shadow-xl mb-6">
        <div class="card-body">
            <div class="flex justify-between items-center">
                <h2 class="card-title">{{ evaluation.name }}</h2>
                <div>
                    {% if evaluation.status == 'pending' %}
                        <span class="badge badge-warning badge-lg">待处理</span>
                    {% elif evaluation.status == 'running' %}
                        <span class="badge badge-info badge-lg">进行中</span>
                    {% elif evaluation.status == 'completed' %}
                        <span class="badge badge-success badge-lg">已完成</span>
                    {% elif evaluation.status == 'failed' %}
                        <span class="badge badge-error badge-lg">失败</span>
                    {% else %}
                        <span class="badge badge-lg">{{ evaluation.status }}</span>
                    {% endif %}
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                <div>
                    <p class="font-semibold">被评估模型</p>
                    <p class="text-lg">{{ model.display_name }}</p>
                </div>
                <div>
                    <p class="font-semibold">裁判模型</p>
                    <p class="text-lg">{{ judge_model.display_name if judge_model else '-' }}</p>
                </div>
                <div>
                    <p class="font-semibold">生成参数</p>
                    <p>温度: {{ evaluation.temperature }}, 最大Token: {{ evaluation.max_tokens }}</p>
                    <p>Top-K: {{ evaluation.top_k or 20 }}, Top-P: {{ evaluation.top_p or 0.8 }}</p>
                </div>
                <div>
                    <p class="font-semibold">并发设置</p>
                    <p>生成并发数: {{ evaluation.eval_batch_size or 4 }}, 裁判评估并发数: {{ evaluation.judge_worker_num or 1 }}</p>
                </div>
                <div>
                    <p class="font-semibold">创建时间</p>
                    <p>{{ evaluation.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</p>
                </div>
            </div>
            
            <!-- 进行中的动画 -->
            {% if evaluation.status == 'running' or evaluation.status == 'pending' %}
                <div class="mt-4">
                    <div class="progress-container">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-sm font-medium">评估进度</span>
                            <span class="text-sm text-gray-600" id="progress-text">计算中...</span>
                        </div>
                        <progress class="progress progress-info w-full" id="progress-bar" value="0" max="100"></progress>
                        <div class="flex justify-between items-center mt-2">
                            <span class="text-xs text-gray-500" id="progress-detail">正在计算进度...</span>
                            <span class="text-xs text-gray-500">页面将自动刷新</span>
                        </div>
                    </div>
                </div>
            <!-- 结果摘要 -->
            {% elif evaluation.status == 'completed' and evaluation.result_summary %}
                <div class="divider"></div>
                <h3 class="text-lg font-semibold mb-4">评估结果摘要</h3>
                {% if evaluation.result_summary.get("error") %}
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        <span>评估摘要加载失败: {{ evaluation.result_summary.error }}
                            {% if evaluation.result_summary.raw_output %}
                            <br>原始输出: {{ evaluation.result_summary.raw_output | truncate(200) }}
                            {% endif %}
                            {% if evaluation.result_summary.error_detail %}
                            <br>详情: {{ evaluation.result_summary.error_detail }}
                            {% endif %}
                        </span>
                    </div>
                {% elif evaluation.result_summary is mapping and evaluation.result_summary %}
                <div class="overflow-x-auto">
                    <table class="table table-zebra w-full">
                        <thead>
                            <tr>
                                <th>模型</th>
                                <th>数据集</th>
                                <th>指标</th>
                                <th>子集</th>
                                <th>数量</th>
                                <th>得分</th>
                                <th>类别</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for report_key, report_data in evaluation.result_summary.items() %}
                                {% if report_data.get('metrics') %}
                                    {% for metric in report_data.metrics %}
                                        {% if metric.get('categories') %}
                                            {% for category in metric.categories %}
                                                {% if category.get('subsets') %}
                                                    {% for subset in category.subsets %}
                                                    <tr>
                                                        <td>{{ report_data.get('model_name', model.display_name) }}</td>
                                                        <td>{{ report_data.get('dataset_name', report_key.split('/')[0]) }}</td>
                                                        <td>{{ metric.get('name', 'N/A') }}</td>
                                                        <td>{{ subset.get('name', 'N/A') }}</td>
                                                        <td>{{ subset.get('num', 'N/A') }}</td>
                                                        <td>{{ "%.3f"|format(subset.get('score')) if subset.get('score') is not none else '-' }}</td>
                                                        <td>
                                                            {% set cat_name = category.get('name') %}
                                                            {% if cat_name is iterable and cat_name is not string %}
                                                                {{ cat_name | join(', ') }}
                                                            {% else %}
                                                                {{ cat_name | default('N/A') }}
                                                            {% endif %}
                                                        </td>
                                                    </tr>
                                                    {% endfor %}
                                                {% else %} 
                                                    <tr>
                                                        <td>{{ report_data.get('model_name', model.display_name) }}</td>
                                                        <td>{{ report_data.get('dataset_name', report_key.split('/')[0]) }}</td>
                                                        <td>{{ metric.get('name', 'N/A') }}</td>
                                                        <td>-</td>
                                                        <td>{{ category.get('num', 'N/A') }}</td>
                                                        <td>{{ "%.3f"|format(category.get('score')) if category.get('score') is not none else '-' }}</td>
                                                        <td>
                                                            {% set cat_name = category.get('name') %}
                                                            {% if cat_name is iterable and cat_name is not string %}
                                                                {{ cat_name | join(', ') }}
                                                            {% else %}
                                                                {{ cat_name | default('N/A') }}
                                                            {% endif %}
                                                        </td>
                                                    </tr>
                                                {% endif %}
                                            {% endfor %}
                                        {% else %} 
                                            <tr>
                                                <td>{{ report_data.get('model_name', model.display_name) }}</td>
                                                <td>{{ report_data.get('dataset_name', report_key.split('/')[0]) }}</td>
                                                <td>{{ metric.get('name', 'N/A') }}</td>
                                                <td>-</td>
                                                <td>{{ metric.get('num', 'N/A') }}</td>
                                                <td>{{ "%.3f"|format(metric.get('score')) if metric.get('score') is not none else '-' }}</td>
                                                <td>-</td>
                                            </tr>
                                        {% endif %}
                                    {% endfor %}
                                {% elif report_data.get('name') and report_data.get('score') is not none %}
                                    <tr>
                                        <td>{{ report_data.get('model_name', model.display_name) }}</td>
                                        <td>{{ report_data.get('dataset_name', report_key) }}</td>
                                        <td>{{ report_data.get('metric_name', 'Overall') }}</td>
                                        <td>{{ report_data.get('subset_name', '-') }}</td>
                                        <td>{{ report_data.get('num', 'N/A') }}</td>
                                        <td>{{ "%.3f"|format(report_data.get('score')) }}</td>
                                        <td>{{ report_data.get('category_name', 'default') }}</td>
                                    </tr>
                                {% else %}
                                     <tr>
                                        <td colspan="7" class="text-center text-error-content bg-error bg-opacity-20">
                                            无法解析报告条目: "{{ report_key }}".<br>
                                            <span class="text-xs">数据: {{ report_data | tojson | truncate(300) }}</span>
                                        </td>
                                    </tr>
                                {% endif %}
                            {% else %}
                                <tr>
                                    <td colspan="7" class="text-center text-neutral-content">没有可显示的摘要数据。</td>
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                     <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-2"></i>
                        <span>评估已完成，但结果摘要为空或格式不正确。</span>
                    </div>
                {% endif %}
            {% elif evaluation.status == 'failed' %}
                <div class="alert alert-error mt-4">
                    <i class="fas fa-exclamation-circle"></i>
                    <span>评估失败: {{ evaluation.result_summary.error if evaluation.result_summary and evaluation.result_summary.error else '未知错误' }}</span>
                </div>
            {% endif %}
        </div>
    </div>
    
    <!-- 数据集信息 -->
    <div class="card bg-base-100 shadow-xl mb-6">
        <div class="card-body">
            <h2 class="card-title">
                <i class="fas fa-database mr-2"></i> 评估数据集
            </h2>
            <div class="overflow-x-auto">
                <table class="table w-full">
                    <thead>
                        <tr>
                            <th>数据集名称</th>
                            <th>子数据集</th>
                            <th>分割</th>
                            <th>类型</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for info in datasets_info %}
                            <tr>
                                <td>{{ info.dataset.name }}</td>
                                <td>{{ info.subset or '-' }}</td>
                                <td>{{ info.split or '-' }}</td>
                                <td>{{ info.dataset.format }}</td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- 新增：跳转到详细结果页面的按钮 -->
    {% if evaluation.status == 'completed' %}
    <div class="card bg-base-100 shadow-xl mb-6">
        <div class="card-body">
            <div class="flex justify-between items-center">
                <h2 class="card-title">
                    <i class="fas fa-list-alt mr-2"></i> 详细评估结果
                </h2>
                <div class="flex gap-2">
                    <!-- Excel导出按钮 -->
                    <button class="btn btn-success btn-sm" 
                            title="导出全部评估结果为Excel文件"
                            onclick="startDownload()">
                        <i class="fas fa-download mr-1"></i> 导出Excel
                    </button>
                    <a href="{{ url_for('evaluations.view_detailed_results', evaluation_id=evaluation.id) }}" class="btn btn-primary btn-sm">
                        <i class="fas fa-search-plus mr-1"></i> 查看并搜索详细结果
                    </a>
                </div>
            </div>
        </div>
    </div>
    {% elif evaluation.status == 'failed' %}
     <div class="card bg-base-100 shadow-xl mb-6">
        <div class="card-body">
             <h2 class="card-title">
                <i class="fas fa-list-alt mr-2"></i> 详细评估结果
            </h2>
            <div class="alert alert-warning mt-4">
                 <i class="fas fa-exclamation-triangle mr-2"></i>
                 <span>评估失败，无法查看详细结果。</span>
            </div>
        </div>
    </div>
    {% endif %}

</div>

<!-- 删除确认模态框 -->
<input type="checkbox" id="delete-modal" class="modal-toggle" />
<div class="modal">
    <div class="modal-box">
        <h3 class="font-bold text-lg">确认删除</h3>
        <p class="py-4">您确定要删除评估 "{{ evaluation.name }}" 吗？此操作无法撤销。</p>
        <div class="modal-action">
            <form method="POST" action="{{ url_for('evaluations.delete_evaluation', evaluation_id=evaluation.id) }}">
                {% from "_form_helpers.html" import render_csrf_token %}
                {{ render_csrf_token() }}
                <button type="submit" class="btn btn-error">删除</button>
            </form>
            <label for="delete-modal" class="btn btn-outline">取消</label>
        </div>
    </div>
</div>

<!-- 下载进度模态框 -->
<input type="checkbox" id="download-modal" class="modal-toggle" />
<div class="modal">
    <div class="modal-box">
        <h3 class="font-bold text-lg">
            <i class="fas fa-download mr-2"></i>正在准备Excel文件
        </h3>
        <div class="py-4">
            <p class="mb-4">正在导出评估结果，请稍候...</p>
            <progress class="progress progress-primary w-full"></progress>
            <p class="text-sm text-gray-500 mt-2">
                正在准备和下载Excel文件，请不要关闭页面。<br>
                下载完成后将自动关闭此提示。
            </p>
        </div>
        <div class="modal-action">
            <label for="download-modal" class="btn btn-outline">
                取消下载
            </label>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
    const evaluationStatus = '{{ evaluation.status }}';
    const evaluationId = '{{ evaluation.id }}';
    const needsRefresh = (evaluationStatus === 'running' || evaluationStatus === 'pending');

    // 进度更新函数
    function updateProgress() {
        fetch(`/evaluations/api/progress/${evaluationId}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error('获取进度失败:', data.error);
                    return;
                }
                
                // 检查状态是否发生变化
                if (data.status !== evaluationStatus) {
                    console.log(`评估状态从 ${evaluationStatus} 变为 ${data.status}`);
                    clearInterval(progressInterval);
                    window.location.reload();
                    return;
                }
                
                const progressBar = document.getElementById('progress-bar');
                const progressText = document.getElementById('progress-text');
                const progressDetail = document.getElementById('progress-detail');
                
                if (progressBar && progressText && progressDetail) {
                    const percentage = data.progress_percentage || 0;
                    progressBar.value = percentage;
                    progressText.textContent = `${percentage}%`;
                    
                    if (data.total_prompts > 0) {
                        progressDetail.textContent = `已完成 ${data.completed_prompts} / ${data.total_prompts} 个问题`;
                    } else {
                        progressDetail.textContent = '正在计算总问题数...';
                    }
                }
            })
            .catch(error => {
                console.error('获取进度失败:', error);
            });
    }

    if (needsRefresh) {
        // 立即更新一次进度
        updateProgress();
        
        // 设置定时器定期更新进度
        const progressInterval = setInterval(updateProgress, 2000);
        
        // 额外的状态检查定时器（作为备用）
        const statusCheckInterval = setInterval(function() {
            fetch(`/evaluations/api/status/${evaluationId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.status !== evaluationStatus) {
                        console.log(`状态检查：评估状态从 ${evaluationStatus} 变为 ${data.status}`);
                        clearInterval(progressInterval);
                        clearInterval(statusCheckInterval);
                        window.location.reload();
                    }
                })
                .catch(error => {
                    console.error('状态检查失败:', error);
                });
        }, 10000);
    }

    // 下载进度相关函数
    function startDownload() {
        showDownloadProgress();
        
        // 构建下载URL
        var downloadUrl = "{{ url_for('evaluations.export_to_excel', evaluation_id=evaluation.id) }}";
        
        // 使用fetch API下载文件
        fetch(downloadUrl, {
            method: 'GET',
            headers: {
                'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('下载请求失败: ' + response.status);
            }
            return response.blob();
        })
        .then(blob => {
            // 创建下载链接
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            // 使用简单的文件名
            var timestamp = new Date().toISOString().slice(0,19).replace(/:/g, '-');
            a.download = 'evaluation_results_' + timestamp + '.xlsx';
            
            document.body.appendChild(a);
            a.click();
            
            // 清理
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            
            hideDownloadProgress();
        })
        .catch(error => {
            console.error('下载失败:', error);
            hideDownloadProgress();
            alert('下载失败: ' + error.message);
        });
    }

    function showDownloadProgress() {
        var modal = document.getElementById('download-modal');
        if (modal) {
            modal.checked = true;
        }
    }

    function hideDownloadProgress() {
        var modal = document.getElementById('download-modal');
        if (modal) {
            modal.checked = false;
        }
    }
</script>
{% endblock %} 